#!/usr/bin/env node
'use strict';

/**
 * This script creates pages for all examples for the website.
 */

const fs = require('fs');
const examples = require('../site/_data/examples.json');
const svg2png = require('svg2png-many');

function createPage(example) {
  return `---
layout: page
${example.description ? `description: "${example.description.replace(/"/g, '\\"')}"` : ''}
title: ${example.title}
menu: examples
permalink: /examples/${example.name}.html
image: /examples/${example.name}.png
edit_path: _data/examples.json
---

${example.description || ''}

{% include example.html spec='${example.name}'%}
`;
}

const fileMap = {};

for (const category of Object.keys(examples)) {
  for (const subcategory of Object.keys(examples[category])) {
    for (const example of examples[category][subcategory]) {
      const name = example.name;

      console.log('Processing', name);

      const fileContent = fs.readFileSync(`examples/specs/${name}.vl.json`);

      if (!example.description) {
        const parsed = JSON.parse(fileContent);
        example.description = parsed.description;
      }

      fs.writeFileSync(`site/examples/${name}.md`, createPage(example));
      fileMap[`examples/compiled/${name}.svg`] = `examples/compiled/${name}.png`;
    }
  }
}

svg2png.svg2PngFiles(fileMap);
